using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CHEnhanceEfCore.DataBase;
using CHEnhanceEfCore.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;

namespace CHEnhanceEfCore.Repository
{
    /// <summary>
    /// author: chenhao
    /// </summary>
    public class UserTaskRepository
    {
        private readonly ChEnhanceDbContext _dbContext;

        public UserTaskRepository(ChEnhanceDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<List<UserTask>> selectUserTaskListAsync() => await (from u in _dbContext.userTaskSet select u).ToListAsync();

        public async Task<UserTask> saveAsync(UserTask userTask)
        {
            EntityEntry<UserTask> entityEntry = await _dbContext.userTaskSet.AddAsync(userTask);
            await saveChangeAsync();
            return entityEntry.Entity;
        }

        public async Task<UserTask> selectByIdAsync(Guid id) => await (from u in _dbContext.userTaskSet where u.id == id select u).FirstOrDefaultAsync();

        public async Task<List<UserTask>> selectUserTaskByIds(List<Guid> userTaskIdList) => await (from u in _dbContext.userTaskSet where userTaskIdList.Contains(u.id) select u).ToListAsync();

        public async Task<bool> deletedRangeAsync(List<UserTask> userTaskList)
        {
            _dbContext.userTaskSet.RemoveRange(userTaskList);
            await saveChangeAsync();
            return true;
        }

        private async Task saveChangeAsync() => await _dbContext.SaveChangesAsync();
    }
}